package com.ce.pub.upload.action;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.omg.CORBA.portable.ApplicationException;

import com.ce.framework.context.FrameworkContext;
import com.ce.framework.datamaintain.action.SearchAction;
import com.ce.framework.util.StringUtil;
import com.ce.pub.upload.dao.po.PubFileUploadLog;
import com.ce.sys.login.model.User;
import com.ce.util.DbUtil;
import com.ce.util.NetFileUtil;

public class UploadAction extends SearchAction {
	private static final long serialVersionUID = 1L;
	
	/** 上传后文件 */
	private File[] files;
	
	private String[] filesFileName;

	/** 上传文件是否全为图片 为true时在构建URL时会使用<img src="..."/>，否则使用<a href="...">文件名</a> */
	private boolean img;
	
	/** 文件在服务器上存放的目录 */
	private String type;
	
	private String targetId,targetName,targetUrl,fileIds,fileNames,fileUrls,backFun;
	
	/** URL的分隔元素 */
	private String urlSplit;
	
	/** 保存文件时要删除的文件ID */
	private String delIds;
	
	/** 下载文件的ID */
	private String vcId,fileName;
	
	/** 下载图片时指定的图片宽高 */
	private int width,height;
	
	private List<PubFileUploadLog> oldFile;

	@SuppressWarnings("unchecked")
	public String execute() throws Exception {

		if(type==null || type.length()==0){
			throw new Exception("文件上传类型不能为空");
		}
		oldFile = (List<PubFileUploadLog>) DbUtil.executeHql("from PubFileUploadLog po where po.vcId in ('"+fileIds.replace(",", "','")+"')");
		String oldFileDesc = "";
		StringBuffer tmp = new StringBuffer();
		if(oldFile!=null&&oldFile.size()>0){
			for(int i=0;i<oldFile.size();i++){
				tmp.append("|").append(oldFile.get(i).getVcId()).append(";")
				.append(oldFile.get(i).getVcFilename()).append(";")
				.append(oldFile.get(i).getNfilesize());
			}
		}
		if(tmp.length()>0)
			oldFileDesc = tmp.substring(1);
		this.setAttribute("oldFileDesc", oldFileDesc);
		return "open";
	}
	
	public String search() throws Exception{
		return super.execute();
	}
	
	public String uploadFiles()
	{
		if(StringUtil.isBlank(urlSplit)){
			urlSplit = ",";
		}
		StringBuffer fileUrl = new StringBuffer();//路径
		StringBuffer fName = new StringBuffer();
		StringBuffer ids = new StringBuffer();
		StringBuffer msg = new StringBuffer();
		
		for(int i=0;files!=null&&i<files.length;i++){
			File file = files[i];
			if (file != null && file.length() > 0) {
				String vcId = null;
				try {
					vcId = NetFileUtil.saveFile(file, filesFileName[i],type);
				} catch (Exception e) {
					msg.append("文件[").append(filesFileName[i]).append("]上传失败！失败原因:")
					.append(e.getMessage()).append("\n");
					e.printStackTrace();
				} // 保存文件


				System.out.println("96-fileUrls:>>>>>>>"+fileUrls+"             >>>"+FrameworkContext.path);
				fileUrl.append(urlSplit).append(img?"<img src='":"<a href='").append(FrameworkContext.path).append(NetFileUtil.getFileUrl(vcId))
				.append(img ? "'/>" : "'>" + filesFileName[i] + "</a>");
				fName.append(",").append(filesFileName[i]);
				ids.append(",").append(vcId);
				System.out.println("101- FrameworkContext.path:>>>>>>>"  + FrameworkContext.path);
				System.out.println("NetFileUtil.getFileUrl(vcId):>>>>>>>"+NetFileUtil.getFileUrl(vcId));
			}
		}
		this.setAttribute("msg", msg);
		if (fileIds != null && !fileIds.equals("")) {
			String tmpIds = "'" + fileIds.replaceAll(",", "','") + "'";
			@SuppressWarnings("unchecked")
			List<PubFileUploadLog> fileList = (List<PubFileUploadLog>) DbUtil.executeHql("FROM PubFileUploadLog po where po.vcId in (" + tmpIds + ")");
			Iterator<PubFileUploadLog> it = fileList.iterator();
			while (it.hasNext()) {
				PubFileUploadLog uploadFile = (PubFileUploadLog) it.next();
				fileUrl.append(urlSplit).append(img?"<img src='":"<a href='").append(FrameworkContext.path)
				.append(NetFileUtil.getFileUrl(uploadFile.getVcId())).append(img?"'/>":"'>"+uploadFile.getVcFilename()+"</a>");
				fName.append(",").append(uploadFile.getVcFilename());   
				ids.append(",").append(uploadFile.getVcId());           
			}
		}

		if (StringUtil.isNotBlank(delIds))
			DbUtil.executeSqlUpdate("update pub_t_file_upload_log set vc_del$flag='1' where vc_id in ('"+delIds.replaceAll(",", "','")+"')"); // 将用户删除的文件更新标志位
		if(ids.length()>1){
			fileIds = ids.substring(1);
		}
		else{
			fileIds = "";
		}
		if(fName.length()>1){
			fileNames = fName.substring(1);
		}
		else{
			fileNames = "";
		}
		if(fileUrl.length()>1){
			fileUrls = fileUrl.substring(urlSplit.length());
		}
		else{
			fileUrls = "";
		}

		System.out.println("fileUrls:>>>>>>>"+fileUrls);
		return "result";
	}
	
	public String loadFile(){
		//下载或打开文件
		NetFileUtil.getDownPicFile(vcId, width, height);
		return NONE;
	}
	
	/** 使用flash上传文件时，name=Filedata */
	private String userId;
	private File Filedata;
	private String FiledataFileName;
	
	@SuppressWarnings("deprecation")
	public String flashAddFile() throws Exception{
		if(StringUtil.isBlank(fileName)){//有时不能从request获取fileName参数，此时需手动从QueryString中截取
			fileName = getRequest().getQueryString();
			if(fileName==null)
				fileName = "";
			fileName = fileName.replaceAll(".*&fileName=(.*)", "$1");
		}
		fileName = decodeUnicode(fileName);
		if(StringUtil.isBlank(fileName)){
			fileName = FiledataFileName;
		}
		if(type==null){
			throw new Exception("文件上传类型不能为空");
		}
		User user = User.getUser();
		if(user!=null){
			userId = user.getVcId();
		}
		File file = Filedata;
		if (file != null && file.length() > 0) {
			try {
				NetFileUtil.sendFile(Filedata, fileName, vcId, type, userId);
			} catch (Exception e) {
				e.printStackTrace();
			} // 保存文件
		}
		return this.writeHTML("ok");
	}

    //将flex中使用escape方法转化成的unicode码(%u4E00等)转化回汉字
    public static String decodeUnicode(String dataStr) {
        final StringBuffer buffer = new StringBuffer();
        String tempStr = "";
        String operStr = dataStr;
        if (operStr != null && operStr.indexOf("%") == -1)
            return buffer.append(operStr).toString();
        if (operStr != null && !operStr.equals("")
                && !operStr.startsWith("%")) {
            tempStr = operStr.substring(0, operStr.indexOf("%"));
            operStr = operStr.substring(operStr.indexOf("%"), operStr.length());// operStr字符一定是以unicode编码字符打头的字符串
        }
        buffer.append(tempStr);
        // 循环处理,处理对象一定是以unicode编码字符打头的字符串
        while (operStr != null && !operStr.equals("")&& operStr.startsWith("%")) {
            String charStr = "";
        	if(operStr.startsWith("%u")){
	            tempStr = operStr.substring(0, 6);
	            operStr = operStr.substring(6, operStr.length());
	            charStr = tempStr.substring(2, tempStr.length());
        	}
	        else{
	            tempStr = operStr.substring(0, 3);
	            operStr = operStr.substring(3, operStr.length());
	            charStr = tempStr.substring(1, tempStr.length());
	        }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            if (operStr.indexOf("%") == -1) {
                buffer.append(operStr);
            } else { // 处理operStr使其打头字符为unicode字符
                tempStr = operStr.substring(0, operStr.indexOf("%"));
                operStr = operStr.substring(operStr.indexOf("%"), operStr.length());
                buffer.append(tempStr);
            }
        }
        return buffer.toString();
    }
	/**
	* 开发人：andy
	* 开发日期: 2013-9-16  下午04:23:08
	* 功能描述: 使用flash客户端删除文件
	* 方法的参数和返回值: 
	* @param mapping
	* @param form
	* @param request
	* @param response
	* @return
	* @throws ApplicationException
	*/
	public String flashDelFiles(){
//		String delIds = getParameter("delIds");
//		if (delIds != null && !"".equals(delIds))
//			DictUtil.updateFileLogInfo(delIds, "1"); // 将用户删除的文件更新标志位
		return this.writeHTML( "ok!");
	}

	public File[] getFiles() {
		return files;
	}

	public void setFiles(File[] files) {
		this.files = files;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getBackFun() {
		return backFun;
	}

	public void setBackFun(String backFun) {
		this.backFun = backFun;
	}

	public String getFileIds() {
		return fileIds;
	}

	public void setFileIds(String fileIds) {
		this.fileIds = fileIds;
	}

	public List<PubFileUploadLog> getOldFile() {
		return oldFile;
	}

	public String getTargetId() {
		return targetId;
	}

	public void setTargetId(String targetId) {
		this.targetId = targetId;
	}

	public String getTargetName() {
		return targetName;
	}

	public void setTargetName(String targetName) {
		this.targetName = targetName;
	}

	public String getTargetUrl() {
		return targetUrl;
	}

	public void setTargetUrl(String targetUrl) {
		this.targetUrl = targetUrl;
	}

	public String getDelIds() {
		return delIds;
	}

	public void setDelIds(String delIds) {
		this.delIds = delIds;
	}

	public void setOldFile(List<PubFileUploadLog> oldFile) {
		this.oldFile = oldFile;
	}

	public String getFileNames() {
		return fileNames;
	}

	public void setFileNames(String fileNames) {
		this.fileNames = fileNames;
	}

	public String getFileUrls() {
		return fileUrls;
	}

	public void setFileUrls(String fileUrls) {
		this.fileUrls = fileUrls;
	}

	public String[] getFilesFileName() {
		return filesFileName;
	}

	public void setFilesFileName(String[] filesFileName) {
		this.filesFileName = filesFileName;
	}

	public String getUrlSplit() {
		return urlSplit;
	}

	public void setUrlSplit(String urlSplit) {
		this.urlSplit = urlSplit;
	}

	public boolean isImg() {
		return img;
	}

	public void setImg(boolean isImg) {
		this.img = isImg;
	}

	public String getVcId() {
		return vcId;
	}

	public void setVcId(String vcId) {
		this.vcId = vcId;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public File getFiledata() {
		return Filedata;
	}

	public void setFiledata(File filedata) {
		Filedata = filedata;
	}

	public String getFiledataFileName() {
		return FiledataFileName;
	}

	public void setFiledataFileName(String filedataFileName) {
		FiledataFileName = filedataFileName;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

}
